package org.linlinjava.litemall.core.util.paymentCodeUtil;

import java.security.SecureRandom;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class ExpiringEncryption {

    private static final Duration VALID_DURATION = Duration.ofSeconds(30);

    public static void main(String[] args) throws Exception {
        String originalString = "76345454";
        String secretKey = generateSecretKey();
        System.out.println("secretKey = " + secretKey);

        String encodedString = encrypt(originalString, secretKey);
        System.out.println("Encoded string: " + encodedString);

        String decryptedString = decrypt("XetczQzpAWeZc8z7wB7pOSse3/NxWkGglclnmJ24uj3L5/LhxmjxkQO29WwiXgbN", "kVuAZUupEGdo+qZC6AHZuOt1wqHDYHueJcJAtw3IHyE=");
        System.out.println("Decrypted string: " + decryptedString);
    }

    private static String generateSecretKey() throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        SecureRandom random = new SecureRandom();
        keyGen.init(256, random);
        SecretKey key = keyGen.generateKey();
        return Base64.getEncoder().encodeToString(key.getEncoded());
    }

    private static String encrypt(String input, String secretKey) throws Exception {
        SecretKey key = new SecretKeySpec(Base64.getDecoder().decode(secretKey), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);

        byte[] encryptedBytes = cipher.doFinal((Instant.now().toString() + " " + input).getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    private static String decrypt(String input, String secretKey) throws Exception {
        SecretKey key = new SecretKeySpec(Base64.getDecoder().decode(secretKey), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key);

        byte[] encryptedBytes = Base64.getDecoder().decode(input);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        String decryptedString = new String(decryptedBytes);

        String[] parts = decryptedString.split(" ", 2);
        Instant generatedTime = Instant.parse(parts[0]);
        if (Instant.now().minus(VALID_DURATION).isAfter(generatedTime)) {
            throw new RuntimeException("Decrypted string has expired");
        }
        return parts[1];
    }
}
